﻿using System;
using biz.ritter.javapi.io;
using biz.ritter.javapi.lang;
using biz.ritter.javapi.net;
using Nofs.Net.Fuse.Impl;

namespace Nofs.Net.Execution
{
    public class ExecutionServer : Thread
    {
        private bool _keepGoing;
        private ServerSocket _serverSock;

        private PathTranslator _translator;
        private LogManager _logger;

        public ExecutionServer(
                PathTranslator translator,
                LogManager logger)
        {
            _translator = translator;
            _logger = logger;
        }

        public void Start() //throws IOException 
        {
            _keepGoing = true;
            _serverSock = new ServerSocket(5050);
            start();
        }

        public void Stop()
        {
            try
            {
                _keepGoing = false;
                new Socket("127.0.0.1", 5050).close();
            }
            catch (System.Exception)
            {
            }
            try
            {
                join();
            }
            catch (System.Exception)
            {
            }
            try
            {
                _serverSock.close();
            }
            catch (System.Exception)
            {
            }
        }

        //@Override
        public override void run()
        {
            while (_keepGoing)
            {
                Socket socket = null;
                try
                {
                    socket = _serverSock.accept();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                if (socket != null && !socket.isClosed())
                {
                    ExecutionServerDriver driver = new ExecutionServerDriver(socket, _translator, _logger);
                    driver.setDaemon(true);
                    driver.start();
                }
            }
        }
    }
}
